package com.mygame.message.nats;

import com.mygame.common.codec.DataCodecKit;
import com.mygame.common.utils.TopicUtil;
import com.mygame.message.channel.GameChannelPromise;
import com.mygame.message.channel.IMessageSendFactory;
import com.mygame.common.protobuf.ExternalMessage;
import io.nats.streaming.StreamingConnection;

public class NatsGatewayMessageSendFactory implements IMessageSendFactory {
    private String topic;
    private StreamingConnection streamingConnection;

    public NatsGatewayMessageSendFactory(StreamingConnection sc, String topic) {
        this.topic = topic;
        this.streamingConnection = sc;
    }

    @Override
    public void sendMessage(ExternalMessage message, GameChannelPromise promise) {
        
        int toServerId = message.getToServerId();
        long playerId = message.getPlayerId();
        // 动态创建游戏网关监听消息的topic
        String sendTopic = TopicUtil.generateTopic(topic,toServerId);
        byte[] value = DataCodecKit.encode(message);
        try {
            streamingConnection.publish(sendTopic, value);
        }catch (Exception e){
            System.out.println(e);
        }
        promise.setSuccess();
    }


}
